<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>爱情留言板</title>
    <script src="/Style/js/tailwindcss.js"></script>
    <link href="/Style/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#ec4899',
                        secondary: '#fce7f3',
                    }
                }
            }
        }

    </script>
    <style>
		.message-content {
		  white-space: pre-line; 
		  word-break: break-word; 
		}
    </style>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .message-card {
                @apply bg-white rounded-xl shadow-sm p-4 mb-4 transition-all hover:shadow-md;
            }
            .message-input {
                @apply w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent resize-none;
            }
        }

    </style>
</head>
<body class="bg-gray-50 font-sans">
<!-- 导航栏 -->
<nav class="bg-white shadow-md fixed w-full top-0 z-50">
    <div class="container mx-auto px-4 py-3">
        <div class="flex justify-between items-center">
            <div class="flex items-center">
                <i class="fa fa-heart text-primary text-2xl mr-2"></i>
                <span class="text-xl font-bold text-gray-800">爱情留言板</span>
            </div>

            <div class="hidden md:flex space-x-8">
                <a href="/" class="text-dark hover:text-primary transition-colors py-2">首页</a>
                <a href="/moments" class="text-dark hover:text-primary transition-colors py-2">点点滴滴</a>
                <a href="/photos" class="text-dark hover:text-primary transition-colors py-2">Love Photo</a>
                <a href="/lovelist" class="text-dark hover:text-primary transition-colors py-2">Love List</a>
                <a href="/messages" class="text-primary border-b-2 border-primary font-medium py-2">留言板</a>
                <a href="/couple" class="text-dark hover:text-primary transition-colors py-2">爱情纪念</a>
            </div>

            <div class="flex items-center space-x-4">
                <div class="relative">
                    <button id="user-menu-button" class="flex items-center space-x-2 focus:outline-none">
                        <img id="user-menu-touxiang"
                             src="{{ session.avatar if session.avatar else '/default_avatar.jpg' }}"
                             alt="用户头像" class="w-8 h-8 rounded-full object-cover border-2 border-primary">
                        <span class="hidden md:inline text-gray-700">{{ session.nickname }}</span>
                        <i class="fa fa-chevron-down text-xs text-gray-500"></i>
                    </button>
                    <div id="user-menu"
                         class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10">
                        <a href="#" id="open-profile" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">个人资料</a>
                        <a href="/logout" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">退出登录</a>
                    </div>
                </div>
                <button id="mobile-menu-button" class="md:hidden text-gray-700">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>

        <!-- 移动端菜单 -->
        <div id="mobile-menu" class="hidden md:hidden mt-4 pb-2">
            <a href="/" class="block text-dark hover:text-primary transition-colors py-2">首页</a>
            <a href="/moments" class="block text-dark hover:text-primary transition-colors py-2">点点滴滴</a>
            <a href="/photos" class="block text-dark hover:text-primary transition-colors py-2">Love Photo</a>
            <a href="/lovelist" class="block text-dark hover:text-primary transition-colors py-2">Love List</a>
            <a href="/messages" class="block text-primary font-medium py-2">留言板</a>
            <a href="/couple" class="block text-dark hover:text-primary transition-colors py-2">爱情纪念</a>
        </div>
    </div>
</nav>

<!-- 主内容 -->
<main class="container mx-auto px-4 pt-24 pb-16">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 侧边栏 - 关系状态和快速留言对象 -->
        <div class="lg:col-span-1">
            <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                <h2 class="text-xl font-semibold text-gray-800 mb-6">关系状态</h2>

                <div id="relationship-status">
                    <!-- 关系状态将通过JS动态加载 -->
                    <div class="text-center py-6">
                        <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fa fa-spinner fa-spin text-primary text-3xl"></i>
                        </div>
                        <p class="text-gray-600">加载中...</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md p-6">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">快速留言</h2>

                <div class="mb-4">
                    <label for="message-recipient" class="block text-gray-700 mb-2">选择对象</label>
                    <select id="message-recipient"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        <option value="self">给自己留言</option>
                        <!-- 情侣对象将通过JS动态添加 -->
                    </select>
                </div>

                <div class="mb-4">
                    <label for="quick-message" class="block text-gray-700 mb-2">留言内容</label>
                    <textarea id="quick-message" rows="3" class="message-input" placeholder="输入留言内容..."></textarea>
                </div>

                <button id="send-quick-message"
                        class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 rounded-lg transition-colors flex items-center justify-center">
                    <i class="fa fa-paper-plane mr-2"></i>发送留言
                </button>
            </div>
        </div>

        <!-- 主内容区 - 留言板和搜索 -->
        <div class="lg:col-span-2">
            <!-- 搜索用户 -->
            <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">给其他用户留言</h2>

                <div class="flex">
                    <input type="text" id="user-search" placeholder="输入用户账号搜索..."
                           class="flex-1 px-4 py-3 border border-gray-300 rounded-l-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                    <button id="search-button"
                            class="bg-primary hover:bg-primary/90 text-white font-medium py-3 px-6 rounded-r-lg transition-colors">
                        <i class="fa fa-search mr-1"></i>搜索
                    </button>
                </div>

                <div id="search-results" class="mt-4 hidden">
                    <!-- 搜索结果将通过JS动态加载 -->
                </div>
            </div>

            <!-- 留言板 -->
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-xl font-semibold text-gray-800">留言记录</h2>
                    <div class="flex space-x-2">
                        <button id="show-all" class="px-3 py-1 bg-primary text-white rounded-md text-sm">全部</button>
                        <button id="show-self"
                                class="px-3 py-1 border border-gray-300 rounded-md text-sm hover:bg-gray-100">给自己
                        </button>
                        <button id="show-partner"
                                class="px-3 py-1 border border-gray-300 rounded-md text-sm hover:bg-gray-100">给伴侣
                        </button>
                    </div>
                </div>

                <!-- 留言列表 -->
                <div id="messages-container">
                    <!-- 留言将通过JS动态加载 -->
                    <div class="text-center py-12">
                        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
                        <p class="text-gray-500">加载留言中...</p>
                    </div>
                </div>

                <!-- 空状态 -->
                <div id="no-messages" class="text-center py-12 hidden">
                    <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fa fa-comment-o text-primary text-3xl"></i>
                    </div>
                    <p class="text-gray-600 mb-4">还没有留言</p>
                    <p class="text-gray-500">开始给TA写第一条留言吧~</p>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- 回复模态框 -->
<div id="reply-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-lg mx-4 p-6 transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4">回复留言</h3>

        <input type="hidden" id="reply-message-id">
        <input type="hidden" id="reply-receiver-id">

        <div class="mb-6">
            <label for="reply-content" class="block text-gray-700 mb-2">回复内容</label>
            <textarea id="reply-content" rows="4" class="message-input" placeholder="输入回复内容..."></textarea>
        </div>

        <div class="flex justify-end space-x-3">
            <button id="cancel-reply"
                    class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                取消
            </button>
            <button id="send-reply"
                    class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                发送回复
            </button>
        </div>
    </div>
</div>

<!-- 编辑留言模态框 -->
<div id="edit-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-lg mx-4 p-6 transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4">编辑留言</h3>

        <input type="hidden" id="edit-message-id">

        <div class="mb-6">
            <label for="edit-content" class="block text-gray-700 mb-2">留言内容</label>
            <textarea id="edit-content" rows="4" class="message-input" placeholder="输入留言内容..."></textarea>
        </div>

        <div class="flex justify-end space-x-3">
            <button id="cancel-edit"
                    class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                取消
            </button>
            <button id="save-edit"
                    class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                保存修改
            </button>
        </div>
    </div>
</div>

<!-- 确认删除模态框 -->
<div id="delete-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-md mx-4 p-6">
        <h3 class="text-xl font-bold text-gray-800 mb-4">确认删除</h3>
        <p class="text-gray-600 mb-6">确定要删除这条留言吗？此操作不可撤销。</p>

        <input type="hidden" id="delete-message-id">

        <div class="flex justify-end space-x-3">
            <button id="cancel-delete"
                    class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                取消
            </button>
            <button id="confirm-delete"
                    class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">
                确认删除
            </button>
        </div>
    </div>
</div>

<!-- 通知提示 -->
<div id="notification"
     class="fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50">
    <i id="notification-icon" class="mr-2"></i>
    <span id="notification-message"></span>
</div>

<script>
        // 当前用户ID
        const currentUserId = {{ session.get('user_id', 'null') }};
        let partnerId = null;
        let partnerName = '';
        let partnerAvatar = '';
        let currentUser = '';
        // DOM元素
        const relationshipStatusEl = document.getElementById('relationship-status');
        const messageRecipientEl = document.getElementById('message-recipient');
        const quickMessageEl = document.getElementById('quick-message');
        const sendQuickMessageBtn = document.getElementById('send-quick-message');
        const userSearchEl = document.getElementById('user-search');
        const searchButtonEl = document.getElementById('search-button');
        const searchResultsEl = document.getElementById('search-results');
        const messagesContainerEl = document.getElementById('messages-container');
        const noMessagesEl = document.getElementById('no-messages');
        const showAllBtn = document.getElementById('show-all');
        const showSelfBtn = document.getElementById('show-self');
        const showPartnerBtn = document.getElementById('show-partner');

        // 模态框元素
        const replyModalEl = document.getElementById('reply-modal');
        const editModalEl = document.getElementById('edit-modal');
        const deleteModalEl = document.getElementById('delete-modal');
        const replyMessageIdEl = document.getElementById('reply-message-id');
        const replyReceiverIdEl = document.getElementById('reply-receiver-id');
        const replyContentEl = document.getElementById('reply-content');
        const editMessageIdEl = document.getElementById('edit-message-id');
        const editContentEl = document.getElementById('edit-content');
        const deleteMessageIdEl = document.getElementById('delete-message-id');

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查登录状态
            checkLoginStatus();
            // 加载关系状态
            loadRelationshipStatus();

            // 加载留言
            loadMessages();

            // 绑定事件
            bindEvents();
        });




        function checkLoginStatus() {
            fetch('/api/user')
                .then(response => {
                    // 检查响应状态
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.id == currentUserId) {
                        currentUser = data;
                        // 更新导航栏头像
                        const userAvatar = document.getElementById('user-menu-touxiang');
                        if (userAvatar) {
                            userAvatar.src = currentUser.avatar || 'default_avatar.jpg';
                            // 保持头像错误处理
                            userAvatar.onerror = function() {
                                this.src = 'default_avatar.jpg';
                            };
                        }
                    } else {
                    window.location.href = '/login'
                    }
                })
                .catch(error => {
                    console.error('检查登录状态失败:', error);
                    // 请求失败时也跳转到登录页
                    window.location.href = '/login';
                });
        }



        // 绑定所有事件处理程序
        function bindEvents() {
            // 快速留言发送
            sendQuickMessageBtn.addEventListener('click', sendQuickMessage);

            // 搜索用户
            searchButtonEl.addEventListener('click', searchUsers);
            userSearchEl.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') searchUsers();
            });

            // 筛选留言
            showAllBtn.addEventListener('click', function() {
                setActiveFilter(showAllBtn);
                loadMessages(); // 不传递筛选参数，显示所有留言
            });

            showSelfBtn.addEventListener('click', function() {
                setActiveFilter(showSelfBtn);
                // 筛选条件：接收者是自己 或者 发送者和接收者都是自己
                loadMessages('self'); // 使用特殊标记'self'表示筛选给自己的留言
            });

            showPartnerBtn.addEventListener('click', function() {
                setActiveFilter(showPartnerBtn);
                if (partnerId) {
                    // 筛选条件：与伴侣相关的所有留言（发给伴侣或来自伴侣）
                    loadMessages(partnerId);
                } else {
                    showNotification('没有情侣关系', 'error');
                }
            });

            // 回复模态框
            document.getElementById('send-reply').addEventListener('click', sendReply);
            document.getElementById('cancel-reply').addEventListener('click', closeReplyModal);

            // 编辑模态框
            document.getElementById('save-edit').addEventListener('click', saveEdit);
            document.getElementById('cancel-edit').addEventListener('click', closeEditModal);

            // 删除模态框
            document.getElementById('confirm-delete').addEventListener('click', confirmDelete);
            document.getElementById('cancel-delete').addEventListener('click', closeDeleteModal);

            // 用户菜单切换
            const userMenuButton = document.getElementById('user-menu-button');
            const userMenu = document.getElementById('user-menu');
            if (userMenuButton && userMenu) {
                userMenuButton.addEventListener('click', function(event) {
                    event.stopPropagation();
                    userMenu.classList.toggle('hidden');
                });
            }

            // 移动端菜单切换
            const mobileMenuButton = document.getElementById('mobile-menu-button');
            const mobileMenu = document.getElementById('mobile-menu');
            if (mobileMenuButton && mobileMenu) {
                mobileMenuButton.addEventListener('click', function(event) {
                    event.stopPropagation();
                    mobileMenu.classList.toggle('hidden');
                });
            }

            // 点击其他地方关闭菜单
            document.addEventListener('click', function() {
                const userMenu = document.getElementById('user-menu');
                if (userMenu && !userMenu.classList.contains('hidden')) {
                    userMenu.classList.add('hidden');
                }

                const mobileMenu = document.getElementById('mobile-menu');
                if (mobileMenu && !mobileMenu.classList.contains('hidden')) {
                    mobileMenu.classList.add('hidden');
                }
            });
        }

        // 设置激活的筛选按钮样式
        function setActiveFilter(button) {
            [showAllBtn, showSelfBtn, showPartnerBtn].forEach(btn => {
                btn.classList.remove('bg-primary', 'text-white');
                btn.classList.add('border', 'border-gray-300', 'hover:bg-gray-100');
            });

            button.classList.remove('border', 'border-gray-300', 'hover:bg-gray-100');
            button.classList.add('bg-primary', 'text-white');
        }

        // 加载关系状态
        function loadRelationshipStatus() {
            fetch('/api/couple/relationship')
                .then(response => response.json())
                .then(data => {
                    // 清空之前的伴侣信息
                    // partnerId = null;
                    // partnerName = '';
                    // partnerAvatar = '';

                    if (data.in_relationship && data.partner) {
                        // 已建立情侣关系 - 适配新数据结构
                        partnerId = data.partner.id;
                        partnerName = data.partner.nickname;
                        partnerAvatar = data.partner.avatar || '/static/default_avatar.jpg';

                        relationshipStatusEl.innerHTML = `
                            <div class="text-center">
                                <div class="flex items-center justify-center space-x-4 mb-4">
                                    <div class="text-center">
                                        <!-- 由于返回数据中没有self信息，使用当前用户的头像和昵称 -->
                                        <img src="${document.getElementById('user-menu-touxiang').src}"
                                             alt="我的头像" class="w-16 h-16 rounded-full object-cover border-2 border-primary mx-auto mb-2">
                                        <p class="font-medium">{{ session.nickname }}</p>
                                    </div>
                                    <div class="text-2xl text-primary">
                                        <i class="fa fa-heart"></i>
                                    </div>
                                    <div class="text-center">
                                        <img src="${partnerAvatar}"
                                             alt="${partnerName}的头像" class="w-16 h-16 rounded-full object-cover border-2 border-primary mx-auto mb-2">
                                        <p class="font-medium">${partnerName}</p>
                                    </div>
                                </div>
                                <p class="text-gray-600">
                                    你们已经绑定关系 <span class="font-semibold text-primary">${data.relationship?.days_together || 0}</span> 天了
                                </p>
                                <p class="text-gray-500 text-sm mt-2">
                                    从 ${data.relationship?.started_at ? new Date(data.relationship.started_at).toLocaleDateString() : ''} 开始
                                </p>
                            </div>
                        `;

                        // 添加情侣到快速留言选项（避免重复添加）
                        if (partnerId && ![...messageRecipientEl.options].some(option => option.value == partnerId)) {
                            const option = document.createElement('option');
                            option.value = partnerId;
                            option.textContent = partnerName;
                            messageRecipientEl.appendChild(option);
                        }

                        // 显示给伴侣的筛选按钮
                        showPartnerBtn.classList.remove('hidden');
                    } else {
                        // 未建立情侣关系
                        relationshipStatusEl.innerHTML = `
                            <div class="text-center py-6">
                                <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                                    <i class="fa fa-heart-o text-primary text-3xl"></i>
                                </div>
                                <p class="text-gray-600 mb-4">你还没有绑定情侣关系</p>
                                <button id="send-request-btn"
                                        class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-colors">
                                    <i class="fa fa-user-plus mr-2"></i>绑定情侣
                                </button>
                            </div>
                        `;

                        // 隐藏给伴侣的筛选按钮
                        showPartnerBtn.classList.add('hidden');

                        // 绑定情侣请求按钮事件
                        document.getElementById('send-request-btn')?.addEventListener('click', function() {
                            window.location.href = '/couple';
                        });
                    }
                })
                .catch(error => {
                    relationshipStatusEl.innerHTML = `
                        <div class="text-center py-6">
                            <p class="text-red-500">加载关系状态失败</p>
                        </div>
                    `;
                    console.error('Error loading relationship status:', error);
                });
        }

        // 加载留言
        function loadMessages(filterType = null) {
            // 显示加载状态
            messagesContainerEl.innerHTML = `
                <div class="text-center py-12">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
                    <p class="text-gray-500">加载留言中...</p>
                </div>
            `;
            noMessagesEl.classList.add('hidden');

            // 构建带筛选参数的URL
            let url = '/api/messages';
            if (filterType) {
                url += `?filter_type=${encodeURIComponent(filterType)}`;
            }

            fetch(url)
                .then(response => {
                    // 检查HTTP响应状态
                    if (!response.ok) {
                        throw new Error(`请求失败: ${response.status} ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(responseData => {
                    // 1. 确保messages是一个数组
                    let messages = [];
                    if (typeof responseData === 'object' && responseData !== null && Array.isArray(responseData.messages)) {
                        messages = responseData.messages;
                    } else {
                        console.warn('API返回的messages格式不符合预期，使用空数组替代');
                    }

                    // 2. 为每条消息添加接收者名称
                    const enrichedMessages = messages.map(msg => {
                        if (typeof msg !== 'object' || msg === null) {
                            console.warn('发现无效的消息对象，已跳过', msg);
                            return null;
                        }

                        let receiverName = msg.receiver_name;
                        let sender_Name =  msg.name;
                        if (msg.receiver_id === currentUserId) {
                            receiverName = '我';
                        } else if (partnerId && msg.receiver_id === partnerId) {
                            receiverName = msg.receiver_name || '伴侣';
                        } 
                         if (msg.sender_id === currentUserId) {
                            sender_Name = '我';
                        }


                        return {
                            id: msg.id || '',
                            sender_id: msg.sender_id || '',
                            receiver_id: msg.receiver_id || '',
                            content: msg.content || '',
                            name: sender_Name || '匿名用户',
                            avatar: msg.avatar || '/static/default_avatar.jpg',
                            created_at: msg.created_at || new Date().toISOString(),
                            parent_id: msg.parent_id,
                            receiver_name: receiverName
                        };
                    }).filter(Boolean);

                    // 3. 应用前端筛选逻辑（与后端保持一致）
                    let filteredMessages = enrichedMessages;

                    // 筛选给自己的留言：接收者是自己
                    if (filterType === 'self') {
                        filteredMessages = enrichedMessages.filter(msg =>
                            msg.receiver_id === currentUserId
                        );
                    }
                    // 筛选与伴侣相关的留言：发给伴侣或来自伴侣
                    else if (filterType && filterType === partnerId.toString()) {
                        filteredMessages = enrichedMessages.filter(msg =>
                            msg.sender_id === partnerId || msg.receiver_id === partnerId
                        );
                    }

                    // 4. 处理空消息列表
                    if (filteredMessages.length === 0) {
                        messagesContainerEl.innerHTML = '';
                        noMessagesEl.classList.remove('hidden');
                        return;
                    }

                    // 5. 按时间排序并渲染
                    filteredMessages.sort((a, b) =>
                        new Date(b.created_at) - new Date(a.created_at)
                    );

                    // 6. 渲染留言列表（保持不变）
                    messagesContainerEl.innerHTML = '';
                    filteredMessages.forEach(message => {
                        // ... 渲染代码保持不变 ...
                        const isSentByMe = message.sender_id === currentUserId;
                        const isSentToMe = message.receiver_id === currentUserId;
                        const messageDirectionClass = isSentByMe ? 'ml-auto bg-secondary' : 'mr-auto bg-gray-100';

                        const date = new Date(message.created_at);
                        const formattedDate = `${date.getFullYear()}-${
                            (date.getMonth() + 1).toString().padStart(2, '0')
                        }-${
                            date.getDate().toString().padStart(2, '0')
                        } ${
                            date.getHours().toString().padStart(2, '0')
                        }:${
                            date.getMinutes().toString().padStart(2, '0')
                        }`;

                        const messageEl = document.createElement('div');
                        messageEl.className = 'message-card';
                        messageEl.innerHTML = `
                            <div class="flex items-start mb-2">
                                <img src="${message.avatar}"
                                     alt="${message.name}的头像"
                                     class="w-10 h-10 rounded-full mr-3"
                                     onerror="this.src='/static/default_avatar.jpg'">
                                <div>
                                    <div class="flex items-center">
                                        <p class="font-medium text-gray-800">${message.name}</p>
                                        <p class="text-xs text-gray-500 ml-2">${formattedDate}</p>
                                    </div>
                                    <p class="text-gray-600 text-sm mt-1">发送给
                                   ${message.receiver_name}</p>
                                </div>
                            </div>

                            <div class="pl-13">
                                <div class="max-w-md p-3 rounded-lg ${messageDirectionClass}">
                                    <div class="message-content text-gray-800">${formatMessageContent(message.content)}</div>
                                </div>

                                <div class="flex mt-2 ml-auto space-x-2">
                                    ${(isSentByMe || isSentToMe) ? `
                                        <button onclick="openReplyModal(${message.id}, ${
                                            isSentByMe ? message.receiver_id : message.sender_id
                                        })" class="text-sm text-primary hover:text-primary/80">
                                            <i class="fa fa-reply mr-1"></i>回复
                                        </button>
                                    ` : ''}

                                    ${isSentByMe ? `
                                        <button onclick="openEditModal(${message.id}, '${escapeQuotes(message.content)}')"
                                                class="text-sm text-gray-600 hover:text-gray-800">
                                            <i class="fa fa-edit mr-1"></i>编辑
                                        </button>
                                        <button onclick="openDeleteModal(${message.id})"
                                                class="text-sm text-red-500 hover:text-red-600">
                                            <i class="fa fa-trash mr-1"></i>删除
                                        </button>
                                    ` : ''}

                                    ${!isSentByMe && isSentToMe ? `
                                        <button onclick="openDeleteModal(${message.id})"
                                                class="text-sm text-red-500 hover:text-red-600">
                                            <i class="fa fa-trash mr-1"></i>删除
                                        </button>
                                    ` : ''}
                                </div>
                            </div>
                        `;

                        messagesContainerEl.appendChild(messageEl);
                    });
                })
                .catch(error => {
                    // 错误处理保持不变
                    console.error('加载留言时发生错误:', error);
                    messagesContainerEl.innerHTML = `
                        <div class="text-center py-12">
                            <p class="text-red-500">加载留言失败：${error.message}</p>
                            <button onclick="loadMessages(${JSON.stringify(filterType)})"
                                    class="mt-4 text-primary hover:underline">
                                重试
                            </button>
                        </div>
                    `;
                });
        }

        // 搜索用户
        function searchUsers() {
            const username = userSearchEl.value.trim();
            if (!username) {
                showNotification('请输入用户名', 'error');
                return;
            }

            // 调用用户搜索API
            fetch(`/api/users/search?username=${encodeURIComponent(username)}`)
                .then(response => {
                    if (!response.ok) throw new Error('搜索失败');
                    return response.json();
                })
                .then(users => {
                    if (users.length === 0) {
                        searchResultsEl.innerHTML = `
                            <div class="p-4 border border-gray-100 rounded-lg text-center">
                                <p class="text-gray-500">没有找到用户 "${username}"</p>
                            </div>
                        `;
                        searchResultsEl.classList.remove('hidden');
                        return;
                    }

                    searchResultsEl.innerHTML = '';
                    users.forEach(user => {
                        if (user.id === currentUserId) return; // 跳过自己

                        const userEl = document.createElement('div');
                        userEl.className = 'p-4 border border-gray-100 rounded-lg flex justify-between items-center mb-2';
                        userEl.innerHTML = `
                            <div class="flex items-center">
                                <img src="${user.avatar || '/static/default_avatar.jpg'}"
                                     alt="${user.nickname}" class="w-10 h-10 rounded-full mr-3"
                                     onerror="this.src='https://picsum.photos/200/200?random=${Math.random()}'">
                                <div>
                                    <p class="font-medium">${user.nickname || user.username}</p>
                                    <p class="text-sm text-gray-500">${user.username}</p>
                                </div>
                            </div>
                            <button onclick="selectUser(${user.id}, '${escapeQuotes(user.nickname || user.username)}')"
                                    class="px-3 py-1 bg-primary text-white rounded text-sm hover:bg-primary/90">
                                留言
                            </button>
                        `;
                        searchResultsEl.appendChild(userEl);
                    });

                    searchResultsEl.classList.remove('hidden');
                })
                .catch(error => {
                    searchResultsEl.innerHTML = `
                        <div class="p-4 border border-gray-100 rounded-lg text-center">
                            <p class="text-red-500">搜索失败: ${error.message}</p>
                        </div>
                    `;
                    searchResultsEl.classList.remove('hidden');
                    console.error('Error searching users:', error);
                });
        }

        // 选择用户进行留言
        function selectUser(userId, userName) {
            // 设置快速留言接收者
            messageRecipientEl.value = userId;

            // 如果没有该选项，添加它
            if (![...messageRecipientEl.options].some(option => option.value == userId)) {
                const option = document.createElement('option');
                option.value = userId;
                option.textContent = userName;
                messageRecipientEl.appendChild(option);
            }

            // 清空搜索框和结果
            userSearchEl.value = '';
            searchResultsEl.innerHTML = '';
            searchResultsEl.classList.add('hidden');

            // 聚焦到留言框
            quickMessageEl.focus();
        }

        // 发送快速留言
        function sendQuickMessage() {
            const receiverId = messageRecipientEl.value === 'self' ? currentUserId : messageRecipientEl.value;
            const content = quickMessageEl.value.trim();

            if (!receiverId || !content) {
                showNotification('请选择接收者并输入留言内容', 'error');
                return;
            }

            fetch('/api/messages', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    receiver_id: parseInt(receiverId),
                    content: content
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showNotification('留言发送成功', 'success');
                    quickMessageEl.value = '';
                    loadMessages();
                } else {
                    showNotification(data.message || '发送失败', 'error');
                }
            })
            .catch(error => {
                showNotification('发送留言失败', 'error');
                console.error('Error sending message:', error);
            });
        }

        // 打开回复模态框
        function openReplyModal(messageId, receiverId) {
            replyMessageIdEl.value = messageId;
            replyReceiverIdEl.value = receiverId;
            replyContentEl.value = '';
            replyModalEl.classList.remove('hidden');
            replyContentEl.focus();
        }

        // 关闭回复模态框
        function closeReplyModal() {
            replyModalEl.classList.add('hidden');
        }

        // 发送回复
        function sendReply() {
            const receiverId = replyReceiverIdEl.value;
            const content = replyContentEl.value.trim();

            if (!receiverId || !content) {
                showNotification('请输入回复内容', 'error');
                return;
            }

            fetch('/api/messages', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    receiver_id: parseInt(receiverId),
                    content: content
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showNotification('回复发送成功', 'success');
                    closeReplyModal();
                    loadMessages();
                } else {
                    showNotification(data.message || '回复失败', 'error');
                }
            })
            .catch(error => {
                showNotification('发送回复失败', 'error');
                console.error('Error sending reply:', error);
            });
        }

        // 打开编辑模态框
        function openEditModal(messageId, content) {
            editMessageIdEl.value = messageId;
            editContentEl.value = content;
            editModalEl.classList.remove('hidden');
            editContentEl.focus();
        }

        // 关闭编辑模态框
        function closeEditModal() {
            editModalEl.classList.add('hidden');
        }

        // 保存编辑
        function saveEdit() {
            const messageId = editMessageIdEl.value;
            const content = editContentEl.value.trim();

            if (!messageId || !content) {
                showNotification('请输入留言内容', 'error');
                return;
            }

            // 调用更新留言的API
            fetch(`/api/messages/${messageId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ content: content })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showNotification('留言已更新', 'success');
                    closeEditModal();
                    loadMessages();
                } else {
                    showNotification(data.message || '更新失败', 'error');
                }
            })
            .catch(error => {
                showNotification('更新留言失败', 'error');
                console.error('Error updating message:', error);
            });
        }

        // 打开删除模态框
        function openDeleteModal(messageId) {
            deleteMessageIdEl.value = messageId;
            deleteModalEl.classList.remove('hidden');
        }

        // 关闭删除模态框
        function closeDeleteModal() {
            deleteModalEl.classList.add('hidden');
        }

        // 确认删除
        function confirmDelete() {
            const messageId = deleteMessageIdEl.value;

            if (!messageId) {
                showNotification('删除失败', 'error');
                return;
            }

            fetch(`/api/messages/${messageId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showNotification('留言已删除', 'success');
                    closeDeleteModal();
                    loadMessages();
                } else {
                    showNotification(data.message || '删除失败', 'error');
                }
            })
            .catch(error => {
                showNotification('删除留言失败', 'error');
                console.error('Error deleting message:', error);
            });
        }

        // 显示通知
        function showNotification(message, type) {
            const notification = document.getElementById('notification');
            const icon = document.getElementById('notification-icon');
            const messageEl = document.getElementById('notification-message');

            if (!notification || !icon || !messageEl) return;

            // 设置通知类型样式
            if (type === 'success') {
                notification.className = 'fixed bottom-4 right-4 px-6 py-3 bg-green-50 text-green-700 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
                icon.className = 'fa fa-check-circle mr-2';
            } else {
                notification.className = 'fixed bottom-4 right-4 px-6 py-3 bg-red-50 text-red-700 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
                icon.className = 'fa fa-exclamation-circle mr-2';
            }

            // 设置消息内容并显示
            messageEl.textContent = message;
            notification.classList.remove('translate-y-20', 'opacity-0');
            notification.classList.add('translate-y-0', 'opacity-100');

            // 3秒后隐藏
            setTimeout(() => {
                notification.classList.remove('translate-y-0', 'opacity-100');
                notification.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }
        
        function formatMessageContent(content) {
		  return content
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#039;');
		}

        function escapeQuotes(str) {
		  if (!str) return '';
		  return str
			.replace(/\\/g, '\\\\') // 先转义反斜杠（防止后续转义字符失效）
			.replace(/'/g, '\\\'')  // 转义单引号
			.replace(/"/g, '\\"')   // 转义双引号
			.replace(/\n/g, '\\n')  // 转义换行符为\n
			.replace(/\r/g, '\\r'); // 转义回车符（部分系统会同时存在\n和\r）
		}

</script>
</body>
</html>
